package com.example.opencvdemo


import android.graphics.Bitmap
import android.util.Log
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.PickVisualMediaRequest
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.Image
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import org.opencv.android.Utils
import org.opencv.imgproc.Imgproc

private const val TAG = "HomeworkCompose"

@Composable
fun HomeworkCompose(modifier: Modifier = Modifier, vm: MyViewModel = MyViewModel()) {
    val context = LocalContext.current

//    LaunchedEffect(key1 = vm) {
//        vm.dataList.collect {
//            Log.e(TAG, "SettingCompose: $it")
//        }
//    }
    Column(
        modifier = modifier.fillMaxSize(),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Image(painter = painterResource(id = R.drawable.y20240528111908), contentDescription = null)

        val singleLauncher = rememberLauncherForActivityResult(
            contract = ActivityResultContracts.PickVisualMedia(),
            onResult = {
                Log.e(TAG, "HomeworkCompose: $it")
                if (it != null) {
                    vm.recognizeImage(context, it)
                }
            }
        )
        Button(onClick = { singleLauncher.launch(PickVisualMediaRequest()) }) {
            Text(text = "打开图片")
        }

        UpdateImage(vm)

        val dataList by vm.dataList.collectAsState()
        Log.e(TAG, "HomeworkCompose: dataList change $dataList")
        Text(text = "${dataList[0]}")
        Text(text = "${dataList[1]}")
        Text(text = "${dataList[2]}")
        Text(text = "${dataList[3]}")
    }
}

@Composable
fun UpdateImage(vm:MyViewModel) {
    Log.e(TAG, "updateImage: in")
    val dstBitmap by vm.recognizedBitmap.collectAsState()
    if ((dstBitmap.width > 10) and (dstBitmap.height > 10)) {
        Image(bitmap = dstBitmap.asImageBitmap(), contentDescription = null)
    }
}